package com.uziot.bucket.jxls.web;

import cn.hutool.core.date.DateUtil;
import com.uziot.bucket.jxls.entity.User;
import com.uziot.bucket.jxls.service.UserService;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@RestController
@RequestMapping("/")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public List<User> list() {
        return userService.listAll();
    }

    @GetMapping("/export")
    public String export(HttpServletRequest request, HttpServletResponse response) {
        String exportTempName = "用户列表导出模板.xlsx";
        String exportFileName = "用户列表导出.xlsx";
        try {
            //获取数据
            List<User> users = userService.listAll();
            //设置jxls相关信息
            Context context = new Context();
            context.putVar("users", users);
            context.putVar("title","用户列表导出");
            context.putVar("time", DateUtil.now());
            context.putVar("exportUser", "王经理");

            //加载模板
            InputStream exIs = this.getClass().getResourceAsStream("/"+exportTempName);
            //生成导出文件
            File tempFile = new File(System.getProperty("java.io.tmpdir") + File.separator + System.currentTimeMillis());
            OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile));
            JxlsHelper.getInstance().processTemplate(exIs, os, context);
            //导出下载
            InputStream is = new BufferedInputStream(new FileInputStream(tempFile));
            byte[] buffer = new byte[is.available()];
            int read = is.read(buffer);
            is.close();
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(exportFileName.getBytes("UTF-8"), "ISO-8859-1"));
            response.addHeader("Content-Length", "" +tempFile.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            return "";
        } catch (Exception e) {
            e.printStackTrace();
            return "文件下载出错";
        }
    }

}
